<template>
  <div class="box-wrap-total">
    <section class="box-operation">
      <div class="box-search">
        <div class="form-group-enquire">
          <Input
            v-model.trim="searchData.name"
            placeholder="筛源名称"
            clearable
            @on-enter="onSearchGetList()"
          ></Input>
        </div>
        <div class="form-group-img" @click="onSearchGetList()">
          <img src="../../assets/images/peach-svg/Frame 23.svg" />
        </div>
        <div class="form-group-addimg" @click="editInfo(1, {})">
          <img src="../../assets/images/peach-svg/add.svg" />
        </div>
      </div>
    </section>

    <!-- <template>
      <el-dialog
        :visible.sync="treeshow"
        class="treetree"
        :modal="true"
        title="权限修改"
      >
        <el-tree
          :data="menuList"
          show-checkbox
          default-expand-all
          node-key="id"
          ref="tree"
        >
        </el-tree>

        <div class="buttons">
          <el-button @click="getCheckedNodes">取消</el-button>
          <el-button @click="getCheckedKeys">确定</el-button>
          <el-button @click="resetChecked">清空</el-button>
        </div>
      </el-dialog>
    </template> -->

    <!-- <myTable :tableColumns="tableColumns" :totalCnt="totalCnt" :tableData="list" :isShowPage="true" :isLoadData="true" @submit="onChangePageSize" :current="searchData.searchPage"></myTable> -->
    <LibVxeTable
      class="staticData"
      :stripe="stripe"
      :tableColumns="tableColumns"
      border="none"
      :tableData="list"
      :slotHeader="slotHeader"
      :PageObj="{
        total: totalCnt,
        currentPage: searchData.page_index,
        pageSize: searchData.page_size,
      }"
      @onPageChange="onChangePageSize"
      resizable
    ></LibVxeTable>
  </div>
</template>
<script>
import { mapGetters } from "vuex";
import utils from "../../commons/utils";
import { commonMixin } from "../../components/ViewInitMixin"; //每一个文件都要包含这个
import { TimePicker } from "iview";
import SearchUser from "../searchUser";
import Request from "../../commons/Request";
import bus from "../../commons/EventBus";
// 全局this
var thatValue;
export default {
  name: "addUserDetailView", //!!这块一定要注意，每一个文件都根据资源path来命名
  components: { TimePicker, SearchUser },
  mixins: [commonMixin],
  data() {
    return {
      stripe: false,
      modal: false,
      searchDate: "",
      searchTime: [
        utils.dateFormat(0, "HH") + "00",
        utils.dateFormat(0, "HH") + "00",
      ],
      searchData: {
        page_index: 1,
        page_size: 30,
        name: "",
      },
      rows: [],
      namelist:[{Id:"internal",Name:"自研"},{Id:"sjb",Name:"数据吧"}],
      treeshow: false,
      menuList: [],
      versionsList: [
        { Id: -1, Name: "全部版本" },
        { Id: 1, Name: "v1" },
        { Id: 2, Name: "v2" },
      ],
      mnoList: {},
      provinceList: {},
      list: [],
      totalCnt: 0,
      info: {},
      channelList: [],
      cityList: [],
      cityInfo: [-1],
      partnerList: [],
      ChannelList: [],
      QdsPartnerList: [],
      QdsPartnerObj: {},
      BusinessList: [],
      BusinessObj: {},
      cityObj: {},
      brandObj: {},
      brandObjCh: {},
      tableColumns: [
        {
          title: "筛源名称",
          field: "label",
          align: "center",
          // slots:{
          //   default:({ row }, h) =>{
          //     let name = row.name==="internal"?"自研":"数据吧"
          //     return [name]
          //   }
          // }
        },
        {
          title: "别名",
          field: "alias",
          align: "center",
        },
        {
          title: "默认",
          field: "default",
          align: "center",
          slots: {
            default: ({ row }, h) => {
              let disabled = false;
              if (this.Perm.add) {
                disabled = false;
              }
              return [
                h(
                  "iSwitch",
                  {
                    props: {
                      value: (1 & row.default) === 1 ? true : false,
                      disabled: disabled,
                      size: "large",
                      beforeChange:thatValue.handleBeforeChange // 阻断属性
                    },
                    on: {
                      "on-change": (value) => {
                        if(value === true) {
                           this.handleType=11
                          }
                          else{
                           this.handleType = 12
                          }
                          this.updateInfo(row);
                      },
                    },
                    nativeOn:{
                            "mousedown":()=>{ // 监听组件原生事件mousedown,此事件在click之前触发
                              thatValue.switchOneInfo = {
                                name:row.name,
                                id:row.id,
                                default:row.default,
                                status:row.status,
                                alias:row.alias
                              }
                            },
                          }
                  },
                  [
                    h("span", {
                      slot: "open",
                      domProps: {
                        innerHTML: "是",
                      },
                    }),
                    h("span", {
                      slot: "close",
                      domProps: {
                        innerHTML: "否",
                      },
                    }),
                  ]
                ),
              ];
            },
          },
        },
        {
          title: "状态",
          field: "status",
          align: "center",
          slots: {
            default: ({ row }, h) => {
              let disabled = false;
              if (this.Perm.add) {
                disabled = false;
              }
              return [
                h(
                  "iSwitch",
                  {
                    props: {
                      value: (1 & row.status) === 1 ? true : false,
                      disabled: disabled,
                      size: "large",
                    },
                    on: {
                      "on-change": (value) => {
                        let info = { id: row.id };
                        value === true
                          ? (this.handleType = 3)
                          : (this.handleType = 4);
                        this.updateInfo(info);
                      },
                    },
                  },
                  [
                    h("span", {
                      slot: "open",
                      domProps: {
                        innerHTML: "启用",
                      },
                    }),
                    h("span", {
                      slot: "close",
                      domProps: {
                        innerHTML: "禁用",
                      },
                    }),
                  ]
                ),
              ];
            },
          },
        },
        {
          title: "操作",
          field: "action",
          // fixed:"right",
          width: 150,
          align: "center",
          slots: {
            default: ({ row }, h) => {
              return this.$AutoFun(() => {
                let hButton = [];

                hButton.push(
                  h("div", {
                    class: "two",
                    on: {
                      click: () => {
                        this.editInfo(2, row);
                      },
                    },
                  })
                );

                hButton.push(
                  h("div", {
                    class: "three",
                    on: {
                      click: () => {
                        this.sureDel(row, -1);
                      },
                    },
                  })
                );

                return hButton;
              });
            },
          },
        },
      ],
      format: {
        name: {
          labelName: "筛源名称",
          labelType: "select",
          placeholder: "请输入筛源名称",
          labelValue:[{id:"internal",name:"自研"},{id:"sjb",name:"数据吧"}]
        },
        alias: {
          labelName: "别名",
          labelType: "text",
          placeholder: "请输入别名",
        },
        default: {
          labelName: "是否默认",
          labelType: "radio",
          labelValue:[{key:1,value:"是"},{key:2,value:"否"}]
        },
      },
      ruleValidate: {
        name: [
          { required: true, message: "筛源名称不能为空", trigger: "blur" },
        ],
        alias: [{ required: true, message: "别名不能为空", trigger: "blur" }],
      },
      dateOptions: {
        disabledDate(date) {
          return date && date.valueOf() > Date.now();
        },
      },
    };
  },
  computed: {
    ...mapGetters(["UserInfo"]),
  },
  created() {
          thatValue = this
        },
  methods: {
    async initView(isMounted) {
      this.initDate();
      this.initSearchData();
    },
    async initSearchData() {
      // let res = await Request.post("sys/menu", "queryMenuDetail_list");
      // this.menuList = [];
      // if (res.code == 0) {
      //   res.data.ResourceList.forEach((item) => {
      //     let info = this.loopResourceData(item);
      //     this.menuList.push(info);
      //   });
      //   console.log(this.menuList, "this.menuList");
      // }
    },
    loopResourceData(item) {
      let info = {
        id: item.ID,
        label: item.Title,
        Path: item.Name,
        children: [],
        ParentMod: item.Perms.length == 0 && item.Children.length > 0,
        Icon: item.Icon,
      };
      // this.resourceMap.set(info.Path,info.Name);
      item.Children.forEach((childItem) => {
        let childInfo = this.loopResourceData(childItem);
        if (!childInfo.ParentMod || childInfo.children.length > 0) {
          info.children.push(this.loopResourceData(childItem));
        }
      });
      return info;
    },
    // //关闭弹窗
    // getCheckedNodes() {
    //   this.treeshow = false;
    // },
    //添加权限方法
    // async getCheckedKeys() {
    //   this.treeshow = false;
    //   let keylist = this.$refs.tree.getCheckedKeys(); //获取取到的id值
    //   console.log(keylist == "", "keylist");
    //   let kkeys = []; //去除id为0的新数组
    //   let keystring = "";
    //   if (keylist != "") {
    //     keylist.forEach((item) => {
    //       item != 0 && kkeys.push(item); //判断为0删除并加进新数组
    //     });
    //     //转成|隔开的字符串
    //     keystring = kkeys.join("|");
    //   } else {
    //     keystring = "empty";
    //   }
    //   let res = await this.RequestPost("edit_item", {
    //     id: this.rows.id,
    //     name: this.rows.name,
    //     alias: this.rows.alias,
    //     menu_ids: keystring,
    //   });
    //   if (res.code == 0) {
    //     utils.showTip("权限修改成功！");
    //   }
    // },
    resetChecked() {
      this.$refs.tree.setCheckedKeys([]);
    },
    onSearchGetList() {
      this.searchData.page_index = 1;
      this.getList();
    },
    //点击权限按钮弹窗
    // async trees(row) {
    //   this.rows = row; //全局row信息
    //   this.treeshow = true;
    //   let res = await Request.post("sys/menu", "queryMenuDetail_list", {
    //     role_id: row.id,
    //   });
    //   let menucheckList = []; //二级菜单数组
    //   let menucheckListids = []; //二级菜单ID数组
    //   if (res.code == 0) {
    //     if (res.data.ResourceList != null && res.data != null) {
    //       res.data.ResourceList.forEach((item) => {
    //         item.Children.forEach((item2) => {
    //           menucheckList.push(item2);
    //         });
    //       });
    //     }
    //   }
    //   menucheckList.forEach((item) => {
    //     menucheckListids.push(item.ID);
    //   });
    //   this.$refs.tree.setCheckedKeys(menucheckListids); //把已勾选的权限id显示
    // },
    async getList() {
      utils.showLoading();
      let res = await this.RequestPost("query_list", this.searchData);
      console.log(res);
      if (res.code == 0 && res.data != null) {
        this.list = [];
        if (res.data.list != null) this.list = res.data.list;
        this.totalCnt = res.data.total;
        // this.list.push({"totalName":"合计","Cnt":res.data.TotalUserCnt});
      }
      await utils.sleepMs(500);
      utils.hideLoading();
    },
    //添加 编辑筛源
    async editInfo(type, row) {
      console.log(type);
      this.handleType = type;
      let title = "";
      let info = {};
      if (this.handleType == 1) {
        title = "添加筛源";
        info = {
          name: "",
          alias: "",
          default:1
        };
      } else {
        if (row.Status > 1) {
          this.format.Status.labelDisabled = true;
        }
        title = "编辑筛源";
        info = {
          id: row.id,
          label:row.label,
          name: row.name,
          alias: row.alias,
          default:row.default
        };
      }
      this.formPopIndex = await utils.showFormPage(
        {
          title: title,
          el: this.$parent.$el,
          labelWidth: 150,
          width: 700,
          cancelBtnStatus: 0,
        },
        info,
        this.format,
        this.ruleValidate,
        this.updateInfo,
        this.onSelectChange
      );
    },
    async updateInfo(info) {
      utils.showLoading();
      let code = -1;
      let actionName = "";
      let tipText = "";
      let postData = utils.cloneObj(info);
      if (this.handleType === 1) {
        actionName = "add_item";
        tipText = "添加成功！";
        if(this.list.length==0){
          postData["default"]=1
        }else{
          postData["default"]=2
        }
        postData["label"]=this.namelist.find(item=>item.Id==postData.name).Name
      } else if (this.handleType === 2) {
        actionName = "edit_item";
        tipText = "修改成功！";
      } else if (this.handleType === 3) {
        actionName = "edit_item";
        tipText = "启用成功！";
        postData = {"id":postData.id,"status":1};
      } else if (this.handleType === 4) {
        actionName = "edit_item";
        tipText = "禁用成功！";
        postData = {"id":postData.id,"status":2};
      }else if (this.handleType === 11) {
        actionName = "edit_item";
        tipText = "启用成功！";
        postData = {"id":postData.id,"status":postData.status,"default":1};
      } else if (this.handleType === 12) {
        actionName = "edit_item";
        tipText = "禁用成功！";
        postData = {"id":postData.id,"status":postData.status,"default":2};
      } else if (this.handleType === -1) {
        actionName = "del_item";
        tipText = "删除成功！";
        postData = { id: postData.id };
      }
      let res = await this.RequestPost(actionName, postData);
      code = res.code;
      if (code == 0) {
        utils.hideFormPage(this.formPopIndex);
        await utils.sleepMs(1000);
        this.onSearchGetList();
        utils.showTip(tipText);
      }else{
        utils.shadowModel(
        {
          title: "报错提示",
          icon: require("../../assets/images/peach-svg/Frame 427318277 (1).svg"),
          modalContent: res.data,
        },
      );
      }
      utils.hideLoading();
    },
    //删除
    sureDel(item, type) {
      this.handleType = -1;
      let label=item.name=='sjb'?'数据吧':item.name=='internal'?'自研':item.name
      utils.shadowModel(
        {
          title: "删除提示",
          icon: require("../../assets/images/peach-svg/Frame 427318277 (1).svg"),
          modalContent: "确认删除 " + label + " ?",
          callBackArgs: { id: item.id },
        },
        (res) => {
          let code = res.code;
          if (code == 0) {
            let data = res.data;
            this.updateInfo(data);
          }
        }
      );
    },
    onChangePageSize(page, pageSize) {
      this.modal = true;
      this.searchData.page_index = page;
      this.searchData.page_size = pageSize;
      this.getList();
    },
    changeDate(val) {
      var b = val[0];
      var s = val[1];
      this.searchData.searchBeginDay = parseInt(b.replace(/-/g, ""));
      this.searchData.searchEndDay = parseInt(s.replace(/-/g, ""));
      this.onSearchGetList();
    },
    changeTime(val) {
      if (val[0] != "") {
        this.searchTime = val;
      } else {
        this.searchTime = ["00:00", "23:59"];
      }
      this.searchData.searchBeginDay = this.searchTime[0].split(":")[0];
      this.searchData.searchEndDay = this.searchTime[1].split(":")[0];
    },
    initDate() {
      let lastDay = utils.dateFormat(
        utils.getServerSysTime() - 86400,
        "yyyy-MM-dd"
      );
      let nowDay = utils.dateFormat(utils.getServerSysTime(), "yyyy-MM-dd");
      var mycars = new Array();
      mycars[0] = lastDay;
      mycars[1] = nowDay;
      this.searchDate = mycars;
      this.changeDate(mycars);
    },
    slotHeader(h) {
      return [
        h("div", {
          class: { allCount: true },
          style: { "margin-left": "10px" },
        }),
      ];
    },
    handleBeforeChange () {
            console.log("handleBeforeChange:",this.switchOneInfo)
            return new Promise((resolve) => {
                this.$Modal.confirm({
                    title: '切换确认',
                    content: '您确认要切换'+this.switchOneInfo.name+'('+this.switchOneInfo.alias+')'+'为默认状态吗？',
                    onOk: () => {
                        resolve();
                    }
                });
            });
          },
    filterPartner(item) {
      // console.log("item ",item)
      if (item.Id == -1) return true;
      if (this.searchData.searchBusinessId == -1) return true;
      return item.BusinessId == this.searchData.searchBusinessId;
    },
  },
};
</script>
